//
//  KLWeatherViewController.m
//  KL
//
//  Created by mac on 15/12/17.
//  Copyright © 2015年 zhouxubin. All rights reserved.
//

#define KLWeatherKey @"5806a90189a23c81c0d3e4ddd0c813b9"
#define KLWeatherAPI @"http://op.juhe.cn/onebox/weather/query"

#import "KLWeatherViewController.h"
#import <SVProgressHUD.h>
#import "ZBNetWorkTool.h"
#import "KLWeatherResult.h"
#import "KLWeatherCell.h"


@interface KLWeatherViewController () <UITableViewDataSource, UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITextField *cityTextField;
@property (weak, nonatomic) IBOutlet UILabel *weatherLabel;
@property (weak, nonatomic) IBOutlet UILabel *temptureLabel;
@property (weak, nonatomic) IBOutlet UILabel *todayLabel;
@property (weak, nonatomic) IBOutlet UILabel *windLabel;
@property (weak, nonatomic) IBOutlet UILabel *suggestLabel;
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (weak, nonatomic) IBOutlet UILabel *weekLabel;

/** 记录请求的数据 */
@property (nonatomic, strong) KLWeatherResult *result;

@end

@implementation KLWeatherViewController

#pragma mark - 添加查询按钮的点击事件
- (IBAction)searchButton {
    // 退出键盘
    [self.view endEditing:YES];
    
    // 先判断是否输入城市名称
    if (self.cityTextField.text.length == 0) {
        [SVProgressHUD showInfoWithStatus:@"请输入城市名称"];
        return;
    }
    
    // 添加遮罩
    [SVProgressHUD showWithStatus:@"正在努力查询,不要走开..."];
    // 请求数据
    NSString *str = [NSString stringWithFormat:@"%@?cityname=%@&key=%@", KLWeatherAPI, [self converStringWith:self.cityTextField.text], KLWeatherKey];
    
    [[ZBNetWorkTool sharedNetWorkTool] GET:str parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {
        
        // 判断是否请求成功
        if (responseObject == nil) {
            [SVProgressHUD showErrorWithStatus:@"请输入正确的城市哟!"];
            return;
        }
        
        // 移除遮罩
        [SVProgressHUD dismiss];
        KLWeatherResult *result = [KLWeatherResult mj_objectWithKeyValues:responseObject[@"result"][@"data"]];
        self.result = result;
        KLLog(@"%@", responseObject);
        // 更新界面
        [self setUpUI:result];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        KLLog(@"%@", error);
        [SVProgressHUD showErrorWithStatus:@"网络信号貌似不好哟!"];
    }];
}

#pragma mark - 更新界面
- (void)setUpUI:(KLWeatherResult *)result {
    // 当前的天气
    self.weatherLabel.text = result.realtime.weather.info;
    // 当前的温度
    self.temptureLabel.text = [NSString stringWithFormat:@"%@°C", result.realtime.weather.temperature];
    // 今天的时间
    self.todayLabel.text = result.realtime.time;
    // 风
    self.windLabel.text = [NSString stringWithFormat:@"%@  %@", result.realtime.wind.direct, result.realtime.wind.power];
    // 建议
    self.suggestLabel.text = result.life[@"info"][@"chuanyi"][1];
    // 星期几
    self.weekLabel.text = [NSString stringWithFormat:@"星期%@", [self converStringWithAlabo:result.realtime.week]];
    // 刷新表格
    [self.myTableView reloadData];
}
/*
 
 c1df859011821713ba790cbce1f4a2b8
 cityname	string	Y	城市名或城市ID，如："苏州"，需要utf8 urlencode
 dtype	string	N	返回数据格式：json或xml,默认json
 format	int	N	未来6天预报(future)两种返回格式，1或2，默认1
 key	string	Y	你申请的key
 */


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 设置tableview的内边距
    self.myTableView.contentInset = UIEdgeInsetsMake(0, 0, 44, 0);
    self.myTableView.tableFooterView = [[UIView alloc] init];
    // 输入框的左边的搜索图片
    self.cityTextField.leftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iconfont_textField"]];
    self.cityTextField.leftViewMode = UITextFieldViewModeAlways;
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.cityTextField becomeFirstResponder];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.result.weather.count - 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 取出模型
    KLWeatherFuture *future = self.result.weather[indexPath.row + 1];
    KLWeatherCell *cell = [KLWeatherCell weatherCellWith:tableView];
    cell.future = future;
    return cell;
}

#pragma mark - 点击屏幕的时候推出键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark - 字符串转码
- (NSString *)converStringWith:(NSString *)orignal {
    return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)orignal, NULL, NULL, kCFStringEncodingUTF8));
}

#pragma mark - 把阿拉伯数字转换成汉字
- (NSString *)converStringWithAlabo:(NSString *)orignal {
    if ([orignal isEqualToString:@"1"]) {
        return @"一";
    }else if ([orignal isEqualToString:@"2"]) {
        return @"二";
    }else if ([orignal isEqualToString:@"3"]) {
        return @"三";
    }else if ([orignal isEqualToString:@"4"]) {
        return @"四";
    }else if ([orignal isEqualToString:@"5"]) {
        return @"五";
    }else if ([orignal isEqualToString:@"6"]) {
        return @"六";
    }else if ([orignal isEqualToString:@"7"]) {
        return @"七";
    }
    return orignal;
}

@end
